﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Win32;
using System.IO;
using System.Text;
using System.Reflection;
using System.Xml;
using System.Globalization;
using System.Resources;

namespace Srvtools
{
    public delegate void LinqDataSetEventHandler(object sender, EventArgs e);

    [ToolboxItem(true)]
    [Designer(typeof(LinqDataSetDesigner), typeof(IDesigner))]
    [ToolboxBitmap(typeof(UpdateComponent), "Resources.InfoDataSet.ico")]
    public class LinqDataSet : InfoBaseComp, IListSource, IGetValues, IFindContainer, ISupportInitialize
    {
        private bool _isDesignMode;
        private System.ComponentModel.Container components = null;
        private System.Data.DataSet fRealDataSet;
        public CurrencyManager myManager = null;
        private bool fInit = false;
        private bool fInitActive = false;
        private bool fServerModify = false;
        public int LastIndex = -1;
        public string CommandText = "";
        public bool Eof = false;
        public string OrderStr = string.Empty;
        private bool fActive;
        private bool fStreamedActive = false;
        private int fPacketRecords = 100;
        private object fLastKeyValues = null;
        private bool fDeleteIncomplete = true;
        private bool fAlwaysClose = false;
        private string fRemoteName;
        private bool FWizardDesignMode = false;
        internal string refCommandText = "";
        internal string refDBAlias = "";
        public bool bChkSucess = true;
        private string _guid;


        private void InitializeComponent()
        {
            this.fRealDataSet = new System.Data.DataSet();
            ((System.ComponentModel.ISupportInitialize)(this.fRealDataSet)).BeginInit();

            this.fRealDataSet.DataSetName = "NewDataSet";
            this.fRealDataSet.Locale = new System.Globalization.CultureInfo("zh-CN");
            ((System.ComponentModel.ISupportInitialize)(this.fRealDataSet)).EndInit();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        public LinqDataSet()
        {
            InitializeComponent();
        }

        public LinqDataSet(bool isDesignMode)
        {
            _isDesignMode = isDesignMode;

            InitializeComponent();
        }

        public LinqDataSet(System.ComponentModel.IContainer container)
        {
            container.Add(this);
            InitializeComponent();
        }


        [Browsable(false)]
        public string Guid
        {
            get
            {
                return _guid;
            }
            set
            {
                _guid = value;
            }
        }

        [Browsable(false)]
        public System.Data.DataSet RealDataSet
        {
            get { return fRealDataSet; }
            set { fRealDataSet = value; }
        }

        [Category("Infolight"), Description("Indicates whether server transfers the lastest date to client automatically after the data in database changes")]
        public bool ServerModify
        {
            get { return fServerModify; }
            set { fServerModify = value; }
        }

        [Browsable(false)]
        public bool ContainsListCollection
        {
            get
            {
                return true;
            }
        }

        [Category("Infolight"), Description("Remote Name of LinqDataSet"), Editor(typeof(RemoteNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
        public string RemoteName
        {
            get
            {
                return fRemoteName;
            }
            set
            {
                if (!fInit && Active && (!fRemoteName.Trim().Equals(value.Trim())))
                {
                    fRealDataSet.Clear();
                    if (DesignMode)
                    {
                        fRealDataSet.Reset();
                    }
                    Active = false;
                }

                fRemoteName = value;
                if (fInit)
                {
                    Active = fStreamedActive;
                }
            }
        }

        [Category("Infolight"), Description("Indicate whether the data is get when the form loads")]
        public bool AlwaysClose
        {
            get
            {
                return fAlwaysClose;
            }
            set
            {
                fAlwaysClose = value;
            }
        }

        [Category("Infolight")]
        public bool DeleteIncomplete
        {
            get
            {
                return fDeleteIncomplete;
            }
            set
            {
                fDeleteIncomplete = value;
            }
        }

        [Browsable(false)]
        public object LastKeyValues
        {
            get
            {
                return fLastKeyValues;
            }
            set
            {
                fLastKeyValues = value;
            }
        }

        [Category("Infolight"), Description("Specifies the amount of data downloaded in each transfer")]
        public int PacketRecords
        {
            get
            {
                return fPacketRecords;
            }
            set
            {
                fPacketRecords = value;
            }
        }

        [Category("Infolight"), Description("Activate LinqDataSet to get data")]
        public bool Active
        {
            get
            {
                return fActive;
            }
            set
            {
                //if (fInit && !value)
                //    fInitActive = true;

                //if ((null != RemoteName) && !RemoteName.Equals(""))
                //{
                //    if (fInit && !value)
                //    {
                //        try
                //        {
                //            fActive = false;
                //            Eof = true;
                //            LastIndex = -1;
                //        }
                //        finally
                //        {
                //        }
                //    }
                //    else
                //    {
                //        if (value != fActive)
                //        {
                //            if (!value)
                //            {
                //                fRealDataSet.Clear();
                //                fActive = value;
                //                Eof = false;
                //                LastIndex = -1;
                //            }
                //            else
                //            {
                //                //Eof = false;
                //                fActive = value;
                //                string s = RemoteName;
                //                int iPos = s.IndexOf('.');
                //                string s1 = s.Substring(0, iPos);
                //                string s2 = s.Substring(iPos + 1, s.Length - iPos - 1);
                //                DataSet aDataSet = null;

                //                if (!DesignMode && !FWizardDesignMode && !_isDesignMode)
                //                {
                //                    //aDataSet = CliUtils.GetSqlCommand(s1, s2, this, WhereStr, "", CommandText, WhereParam, OrderStr);
                //                    if (PacketRecords > 0)
                //                    {
                //                        aDataSet = CliUtils.LinqExecuteQuery(s1, s2, LastIndex, PacketRecords);
                //                    }
                //                    else
                //                    {
                //                        aDataSet = CliUtils.LinqExecuteQuery(s1, s2);
                //                    }
                //                }
                //                else
                //                {
                //                    string sCurProject = CliUtils.fCurrentProject;
                //                    if (this.DesignMode || _isDesignMode || FWizardDesignMode)
                //                    {
                //                        sCurProject = EditionDifference.ActiveSolutionName();
                //                    }

                //                    //aDataSet = CliUtils.GetSqlCommand(s1, s2, this, WhereStr, sCurProject, CommandText, WhereParam, OrderStr);
                //                    aDataSet = CliUtils.LinqExecuteQuery(s1, s2, sCurProject);
                //                }

                //                if (-1 != PacketRecords)
                //                {
                //                    //DataRow lastrow = null;
                //                    if (aDataSet != null && aDataSet.Tables.Count > 0)
                //                    {
                //                        if (aDataSet.Tables[0].Rows.Count < PacketRecords)
                //                            Eof = true; 

                //                        LastIndex += aDataSet.Tables[0].Rows.Count;
                //                    }
                //                }
                //                else
                //                {
                //                    Eof = true;
                //                }
                //                fRealDataSet.Clear();
                //                if (aDataSet != null)
                //                {
                //                    fRealDataSet.CaseSensitive = true;
                //                    fRealDataSet.Merge(aDataSet);
                //                }
                //            }

                //            if (fActive && fInitActive)
                //                fActive = false;
                //        }
                //    }
                //}
                //else
                //{
                //    fStreamedActive = value;
                //}
            }
        }




        public void SetWizardDesignMode(bool value)
        {
            FWizardDesignMode = value;
        }

        public void SetOrder(string strOrder)
        {
            OrderStr = strOrder;
            Active = false;
            LastIndex = -1;
            Active = true;
        }

        public int GetRecordsCount(string strWhere)
        {
            int i = 0;
            int iPos = RemoteName.IndexOf('.');
            if (iPos > 0)
            {
                string sModule = RemoteName.Substring(0, iPos);
                string sDataSet = RemoteName.Substring(iPos + 1);
                i = CliUtils.GetRecordsCount(sModule, sDataSet, strWhere, CliUtils.fCurrentProject);
            }

            return i;
        }

        public int GetRecordsCount()
        {
            return GetRecordsCount("");
        }

        public IList GetList()
        {
            return ((IListSource)fRealDataSet).GetList();
        }

        public ArrayList GetKeyFields()
        {
            return GetKeyFields("");
        }

        public ArrayList GetKeyFields(string sDataSetName)
        {
            string remoteName = this.RemoteName;
            string[] ss = new string[] { };
            if (remoteName != null && remoteName.Length != 0)
            {
                ss = remoteName.Split(".".ToCharArray());
            }

            if (ss.Length == 2)
            {
                if (sDataSetName == null || sDataSetName.Length == 0)
                {
                    return CliUtils.GetKeyFields(ss[0], ss[1], CliUtils.fCurrentProject);
                }
                else
                {
                    return CliUtils.GetKeyFields(ss[0], sDataSetName, CliUtils.fCurrentProject);
                }
            }
            else
            {
                return null;
            }
        }

        public void BeginInit()
        {
            fInit = true;
        }

        public void EndInit()
        {
            fInit = false;
            if (fInitActive)
                fInitActive = false;
            //OnInitialized
        }

        public DataSet GetRealDataSet()
        {
            return this.fRealDataSet;
        }

        public string[] GetValues(string sKind)
        {
            if (sKind.Equals("RemoteName"))
            {
                string s = EditionDifference.ActiveSolutionName();

                EEPRemoteModule remoteObject = new EEPRemoteModule();
                object[] myRet = remoteObject.GetSqlCommandList(new object[] { (object)"", (object)"", (object)"", (object)"", (object)"", (object)"", (object)s });
                if ((null != myRet))
                {
                    if (0 == (int)(myRet[0]))
                    {
                        string[] sList = (string[])(myRet[1]);
                        return sList;
                    }
                    else
                    {
                        return new string[0] { };
                    }
                }
                else
                    return new string[0] { };
            }
            else
                return new string[0] { };
        }




        public bool GetNextPacket()
        {
            if (Eof) return false;

            //if ((null != RemoteName) && !RemoteName.Equals(""))
            //{
            //    PacketEventArgs e = new PacketEventArgs(PacketEventArgs.PacketState.Before);
            //    OnNextPacket(e);
            //    if (e.Cancel)
            //    {
            //        return false;
            //    }
            //    string s = RemoteName;
            //    int iPos = s.IndexOf('.');
            //    string s1 = s.Substring(0, iPos);
            //    string s2 = s.Substring(iPos + 1, s.Length - iPos - 1);
            //    DataSet aDataSet = null;
            //    //if (s1 == "GLModule" && s2 == "cmdRefValUse")
            //    //{
            //    //    //aDataSet = (DataSet)(CliUtils.ExecuteSql(s1, s2, refCommandText, refDBAlias, true, CliUtils.fCurrentProject, new object[] { this.PacketRecords, LastIndex }));
            //    //}
            //    //else
            //    //{
            //        //aDataSet = (DataSet)(CliUtils.GetSqlCommand(s1, s2, this, WhereStr, "", CommandText, WhereParam));
            //    aDataSet = (DataSet)(CliUtils.LinqExecuteQuery(s1, s2, LastIndex - 1, fPacketRecords));
            //    //}
            //    if (-1 != PacketRecords)
            //    {
            //        if (aDataSet.Tables[0].Rows.Count < PacketRecords)
            //            Eof = true;

            //        LastIndex += aDataSet.Tables[0].Rows.Count;
            //    }

            //    fRealDataSet.Merge(aDataSet);
            //    OnNextPacket(new PacketEventArgs(PacketEventArgs.PacketState.After));
            //}

            return true;
        }

        public bool GetAllPacket()
        {
            int oldPacketRecords = -1;
            DataSet aDataSet = null;
            if (Eof) return false;
            if (!Active) return false;

            if ((null != RemoteName) && !RemoteName.Equals(""))
            {
                string s = RemoteName;
                int iPos = s.IndexOf('.');
                string s1 = s.Substring(0, iPos);
                string s2 = s.Substring(iPos + 1, s.Length - iPos - 1);
                try
                {
                    oldPacketRecords = PacketRecords;
                    PacketRecords = -1;
                    //aDataSet = (DataSet)(CliUtils.GetSqlCommand(s1, s2, this, WhereStr, "", CommandText, WhereParam));
                }
                finally
                {
                    PacketRecords = oldPacketRecords;
                }
                if (-1 != PacketRecords)
                {
                    LastIndex = aDataSet.Tables[0].Rows.Count - 1;
                    Eof = true;
                }
                fRealDataSet.Clear();
                fRealDataSet.Merge(aDataSet);
            }

            return true;
        }

        public delegate void PacketEventHandler(object sender, PacketEventArgs e);
        internal static readonly object EventOnNextPacket = new object();

        [Category("Infolight"), Description("The event ocured when get next packet")]
        public event PacketEventHandler NextPacket
        {
            add { base.Events.AddHandler(EventOnNextPacket, value); }
            remove { base.Events.RemoveHandler(EventOnNextPacket, value); }
        }

        protected void OnNextPacket(PacketEventArgs value)
        {
            PacketEventHandler handler = (PacketEventHandler)base.Events[EventOnNextPacket];
            if (handler != null)
            {
                handler(this, value);
            }
        }

        public DataSet Execute(string sCommandText)
        {
            return Execute(sCommandText, false);
        }

        public DataSet Execute(string sCommandText, bool isReplace)
        {
            return Execute(sCommandText, null, isReplace);
        }

        public DataSet Execute(string sCommandText, ArrayList paramWhere)
        {
            return Execute(sCommandText, null, false, paramWhere);
        }

        public DataSet Execute(string sCommandText, string DBAlias, bool isReplace)
        {
            return Execute(sCommandText, DBAlias, isReplace, null);
        }

        public DataSet Execute(String sCommandText, String DBAlias, bool isReplace, ArrayList paramWhere)
        {
            DataSet dsRet = null;

            int iPos = RemoteName.IndexOf('.');
            if (iPos > 0)
            {
                string sModule = RemoteName.Substring(0, iPos);
                string sDataSet = RemoteName.Substring(iPos + 1);
                refCommandText = sCommandText;
                refDBAlias = DBAlias;
                LastIndex = -1;
                Eof = false;
                dsRet = CliUtils.ExecuteSql(sModule, sDataSet, sCommandText, DBAlias, true, CliUtils.fCurrentProject, new object[2] { this.PacketRecords, LastIndex }, paramWhere);
                LastIndex += this.PacketRecords;
            }

            if (isReplace)
            {
                fRealDataSet.Clear();
                fRealDataSet.Merge(dsRet);
                fRealDataSet.AcceptChanges();
            }

            return dsRet;
        }




        [Browsable(false)]
        public int Position
        {
            get
            {
                if (null != myManager)
                    return myManager.Position;
                else
                    return -1;
            }
            set
            {
                if (null != myManager)
                    myManager.Position = value;
            }
        }

        public bool First()
        {
            bool bRet = false;
            if (null != myManager)
            {
                myManager.Position = 0;
                bRet = true;
            }
            return bRet;
        }

        public bool Prior()
        {
            bool bRet = false;
            if (null != myManager)
            {
                myManager.Position--;
                bRet = true;
            }
            return bRet;
        }

        public bool Next()
        {
            bool bRet = false;
            if (null != myManager)
            {
                myManager.Position++;
                bRet = true;
            }
            return bRet;
        }

        public bool Last()
        {
            bool bRet = false;
            if (null != myManager)
            {
                myManager.Position = fRealDataSet.Tables[0].DefaultView.Count - 1;
                bRet = true;
            }
            return bRet;
        }

        public bool MoveBy(int iSkip)
        {
            bool bRet = false;
            if (null != myManager)
            {
                if (iSkip > 0)
                    for (int i = 0; i < iSkip; i++)
                        myManager.Position++;
                else
                    for (int i = 0; i > iSkip; i--)
                        myManager.Position--;
                bRet = true;
            }
            return bRet;
        }

        public enum state
        {
            Inserted, Edited, Deleted
        }

        public state[] State(string strTalbeName)
        {
            DataTableCollection Tables = this.fRealDataSet.Tables;
            DataTable tab = null;
            int i = Tables.Count;
            for (int j = 0; j < i; j++)
            {
                if (Tables[j].TableName.ToUpper() == strTalbeName.ToUpper())
                {
                    tab = Tables[j];
                    break;
                }
            }
            ArrayList states = new ArrayList();
            if (tab != null)
            {
                if (tab.GetChanges(DataRowState.Added) != null)
                {
                    states.Add(state.Inserted);
                }
                if (tab.GetChanges(DataRowState.Deleted) != null)
                {
                    states.Add(state.Deleted);
                }
                if (tab.GetChanges(DataRowState.Modified) != null)
                {
                    states.Add(state.Edited);
                }
            }
            int m = states.Count;
            state[] myState = new state[m];
            for (int n = 0; n < m; n++)
            {
                myState[n] = (state)states[n];
            }
            return myState;
        }

        public bool IsInserted(string TalbeName)
        {
            bool isInserted = false;
            state[] s = this.State(TalbeName);
            int i = s.Length;
            for (int j = 0; j < i; j++)
            {
                if (s[j] == state.Inserted)
                {
                    isInserted = true;
                    break;
                }
            }
            return isInserted;
        }

        public bool IsUpdated(string TalbeName)
        {
            bool isUpdated = false;
            state[] s = this.State(TalbeName);
            int i = s.Length;
            for (int j = 0; j < i; j++)
            {
                if (s[j] == state.Edited)
                {
                    isUpdated = true;
                    break;
                }
            }
            return isUpdated;
        }

        public bool IsDeleted(string TalbeName)
        {
            bool isDeleted = false;
            state[] s = this.State(TalbeName);
            int i = s.Length;
            for (int j = 0; j < i; j++)
            {
                if (s[j] == state.Deleted)
                {
                    isDeleted = true;
                    break;
                }
            }
            return isDeleted;
        }



        //internal bool RelationsActive = false;
        //protected void OnBeforeApplyUpdates(EventArgs value)
        //{
        //    EventHandler handler = (EventHandler)base.Events[EventOnBeforeApplyUpdates];
        //    if (handler != null)
        //    {
        //        handler(this, value);
        //    }

        //    DataTable mergeTab = new DataTable();
        //    DataSet mergedataset = new DataSet();
        //    DataSet ds = new DataSet();
        //    if (this.Container != null)
        //    {
        //        int i = this.Container.Components.Count;
        //        for (int j = 0; j < i; j++)
        //        {
        //            if (this.Container.Components[j] is InfoBindingSource)
        //            {
        //                InfoBindingSource bs = (InfoBindingSource)this.Container.Components[j];
        //                int m = bs.Relations.Count;
        //                for (int n = 0; n < m; n++)
        //                {
        //                    InfoRelation infoRel = bs.Relations[n];
        //                    ds = this.fRealDataSet;
        //                    if (infoRel.RelationDataSet.GetRealDataSet() == ds)
        //                    {
        //                        if (ds.HasChanges())
        //                        {
        //                            string strTabName = this.RemoteName.Substring(this.RemoteName.IndexOf('.') + 1);
        //                            mergeTab = ds.GetChanges().Tables[strTabName];
        //                            mergedataset = ds.GetChanges();
        //                            if (((LinqDataSet)bs.GetDataSource()).RealDataSet.Tables[0].Rows.Count == 0)
        //                            {
        //                                bs.Set_fEmptyViewMerge();
        //                            }
        //                            ((LinqDataSet)bs.GetDataSource()).RealDataSet.Tables[0].Merge(mergeTab);

        //                            foreach (DataTable tb in ds.Tables)
        //                            {
        //                                if (mergedataset.Tables[tb.TableName] != null)
        //                                {
        //                                    tb.Merge(mergedataset.Tables[tb.TableName]);
        //                                }
        //                            }

        //                            ArrayList keyFields = this.GetKeyFields();
        //                            int p = mergeTab.Rows.Count - 1;
        //                            if (p >= 0 && (mergeTab.Rows[p].RowState == DataRowState.Added || mergeTab.Rows[p].RowState == DataRowState.Modified))
        //                            {
        //                                int x = keyFields.Count;
        //                                object[] keyValues = new object[x];
        //                                for (int y = 0; y < x; y++)
        //                                {
        //                                    keyValues[y] = mergeTab.Rows[p][keyFields[y].ToString()];
        //                                }
        //                                DataRow locRow = ((LinqDataSet)bs.GetDataSource()).RealDataSet.Tables[0].Rows.Find(keyValues);
        //                                if (locRow != null)
        //                                {
        //                                    int a = bs.List.Count;
        //                                    for (int b = 0; b < a; b++)
        //                                    {
        //                                        if (((DataRowView)bs.List[b]).Row == locRow)
        //                                        {
        //                                            if (infoRel.Active)
        //                                            {
        //                                                RelationsActive = true;
        //                                                infoRel.Active = false;
        //                                            }

        //                                            bs.Position = b;
        //                                            break;
        //                                        }
        //                                    }
        //                                }
        //                            }
        //                        }
        //                        break;
        //                    }
        //                }
        //            }
        //        }
        //    }
        //}

        //internal static readonly object EventOnBeforeApplyUpdates = new object();
        //public event EventHandler BeforeApplyUpdates
        //{
        //    add { base.Events.AddHandler(EventOnBeforeApplyUpdates, value); }
        //    remove { base.Events.RemoveHandler(EventOnBeforeApplyUpdates, value); }
        //}

        //protected void OnAfterApplyUpdates(EventArgs value)
        //{
        //    EventHandler handler = (EventHandler)base.Events[EventOnAfterApplyUpdates];
        //    if (handler != null)
        //    {
        //        handler(this, value);
        //    }
        //}
        //internal static readonly object EventOnAfterApplyUpdates = new object();
        //public event EventHandler AfterApplyUpdates
        //{
        //    add { base.Events.AddHandler(EventOnAfterApplyUpdates, value); }
        //    remove { base.Events.RemoveHandler(EventOnAfterApplyUpdates, value); }
        //}


        //public delegate void ApplyErrorEventHandler(object sender, ApplyErrorEventArgs e);
        //internal static readonly object EventOnApplyError = new object();

        //[Category("Infolight"),        Description("The event ocured when apply data encounter errors")]
        //public event ApplyErrorEventHandler ApplyError
        //{
        //    add { base.Events.AddHandler(EventOnApplyError, value); }
        //    remove { base.Events.RemoveHandler(EventOnApplyError, value); }
        //}

        //protected void OnApplyError(ApplyErrorEventArgs value)
        //{
        //    ApplyErrorEventHandler handler = (ApplyErrorEventHandler)base.Events[EventOnApplyError];
        //    if (handler != null)
        //    {
        //        handler(this, value);
        //    }
        //}

        //public virtual bool ApplyUpdates()
        //{
        //    return ApplyUpdates(true);
        //}

        //public virtual bool ApplyUpdates(bool NeedToValidate)
        //{
        //    bool blapplysuccess = true;
        //    if (fRealDataSet.HasChanges())
        //    {
        //        try
        //        {
        //            OnBeforeApplyUpdates(new EventArgs());

        //            if (this.Site != null /*&& NeedToValidate*/)
        //            {
        //                foreach (IComponent comp in this.Site.Container.Components)
        //                {
        //                    if (comp is DefaultValidate)
        //                    {
        //                        DefaultValidate validator = comp as DefaultValidate;
        //                        InfoBindingSource bindingSource = validator.BindingSource;
        //                        if (bindingSource != null)
        //                        {
        //                            if (bindingSource.GetDataSource() != null && bindingSource.GetDataSource() is LinqDataSet
        //                                && (LinqDataSet)bindingSource.GetDataSource() == this)
        //                            {
        //                                bool isDetail = false;
        //                                foreach (DataRelation relation in this.RealDataSet.Relations)
        //                                {
        //                                    if (bindingSource.DataMember == relation.RelationName)
        //                                    {
        //                                        isDetail = true;
        //                                        break;
        //                                    }
        //                                }
        //                                if (NeedToValidate || isDetail)
        //                                {
        //                                    for (int i = 0; i < validator.BindingSource.List.Count; ++i)
        //                                    {
        //                                        DataRowView rowView = validator.BindingSource.List[i] as DataRowView;

        //                                        if (rowView.Row.RowState == DataRowState.Modified || rowView.Row.RowState == DataRowState.Added)
        //                                        {
        //                                            bool isInsert = rowView.Row.RowState == DataRowState.Added;
        //                                            bool CheckDeplicateSucessful = validator.DeplCheck(rowView, isInsert);
        //                                            if (!CheckDeplicateSucessful)
        //                                            {
        //                                                return false;
        //                                            }
        //                                            if (validator.ValidActive == true)
        //                                            {
        //                                                bool CheckNullAndRangeSuccessful = validator.CheckNullAndRange(rowView);
        //                                                bool ValidateSuccessful = validator.ValidateRow(i, rowView);
        //                                                validator.ResetWarnging();
        //                                                if (!CheckNullAndRangeSuccessful || !ValidateSuccessful)
        //                                                {
        //                                                    return false;
        //                                                }
        //                                            }
        //                                        }
        //                                    }
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }

        //            if (DeleteIncomplete)
        //            {
        //                foreach (DataTable table in fRealDataSet.Tables)
        //                {
        //                    ArrayList keys = GetKeyFields(table.TableName);
        //                    ArrayList rows = new ArrayList();
        //                    foreach (DataRow row in table.Rows)
        //                    {
        //                        if (row.RowState != DataRowState.Added)
        //                        {
        //                            continue;
        //                        }

        //                        bool keyIsNull = false;
        //                        foreach (object obj in keys)
        //                        {
        //                            if (row[(string)obj] == null || row[(string)obj] == DBNull.Value)
        //                            {
        //                                keyIsNull = true;
        //                                break;
        //                            }
        //                        }

        //                        if (keyIsNull)
        //                        {
        //                            rows.Add(row);
        //                        }
        //                    }

        //                    foreach (DataRow row in rows)
        //                    {
        //                        table.Rows.Remove(row);
        //                    }
        //                }
        //            }

        //            // End Add
        //            DataSet custDS = new DataSet();
        //            if (fRealDataSet.GetChanges() != null)
        //            {
        //                custDS.Merge(fRealDataSet.GetChanges());//tables...
        //            }

        //            string s = RemoteName;
        //            int iPos = s.IndexOf('.');
        //            string s1 = s.Substring(0, iPos);
        //            string s2 = s.Substring(iPos + 1, s.Length - iPos - 1);

        //            DataSet aDS = new DataSet();
        //            if (this.CommandText != null && this.CommandText.Length != 0)
        //                aDS = CliUtils.UpdateDataSet(s1, s2, custDS, this.CommandText);
        //            else
        //                aDS = CliUtils.UpdateDataSet(s1, s2, custDS, "");

        //            if (aDS == null || aDS.Tables == null)
        //            { return false; }

        //            InfoBindingSource ibsview = null;
        //            if (this.Container != null)
        //            {
        //                foreach (IComponent comp in this.Container.Components)
        //                {
        //                    if (comp is InfoBindingSource)
        //                    {
        //                        InfoBindingSource ibs = comp as InfoBindingSource;
        //                        foreach (InfoRelation relation in ibs.Relations)
        //                        {
        //                            if (relation.RelationDataSet == this)// find view
        //                            {
        //                                ibsview = ibs;
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //            }

        //            if (fServerModify)
        //            {
        //                int m = 0;
        //                foreach (DataRow row in aDS.Tables[0].Rows)
        //                {
        //                    if (row.RowState == DataRowState.Added)
        //                    {
        //                        break;
        //                    }
        //                    m++;
        //                }
        //                if (m < aDS.Tables[0].Rows.Count)
        //                {
        //                    DataRow needModifyRow = fRealDataSet.Tables[0].Rows[m];
        //                    foreach (DataRow r in fRealDataSet.Tables[0].Rows)
        //                    {
        //                        if (r.RowState == DataRowState.Added)
        //                        { needModifyRow = r; }
        //                    }

        //                    foreach (DataColumn c in needModifyRow.Table.Columns)
        //                    {
        //                        needModifyRow[c.ColumnName] = aDS.Tables[0].Rows[m][c.ColumnName];
        //                    }
        //                    if (ibsview != null)
        //                    {
        //                        DataSet realDs = ((LinqDataSet)ibsview.GetDataSource()).RealDataSet;
        //                        DataSet ds = realDs.GetChanges(DataRowState.Added);
        //                        if (ds != null)
        //                        {
        //                            DataColumn[] cs = realDs.Tables[0].PrimaryKey;
        //                            DataRow row = ds.Tables[0].Rows[0];

        //                            if (cs.Length != 0)
        //                            {
        //                                List<object> os = new List<object>();
        //                                foreach (DataColumn c in cs)
        //                                {
        //                                    os.Add(row[c.ColumnName]);
        //                                }

        //                                DataRow replaceRow = realDs.Tables[0].Rows.Find(os.ToArray());
        //                                foreach (DataColumn c in needModifyRow.Table.Columns)
        //                                {
        //                                    if (replaceRow.Table.Columns.Contains(c.ColumnName))
        //                                    {
        //                                        replaceRow[c.ColumnName] = needModifyRow[c.ColumnName];
        //                                    }
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //            if (ibsview != null)
        //            {
        //                (ibsview.DataSource as LinqDataSet).RealDataSet.AcceptChanges();
        //                ibsview.Reset_fInEdit();
        //            }

        //            fRealDataSet.AcceptChanges();
        //        }
        //        catch (Exception e)
        //        {
        //            if (fRealDataSet.GetChanges(DataRowState.Deleted) != null
        //                && fRealDataSet.GetChanges(DataRowState.Deleted).Tables[0].Rows.Count > 0 && this.Container != null)
        //            {
        //                bool autoapply = false;
        //                InfoBindingSource ibsview = null;
        //                if (this.Container != null)
        //                {
        //                    foreach (IComponent comp in this.Container.Components)
        //                    {
        //                        if (comp is InfoBindingSource)
        //                        {
        //                            InfoBindingSource ibs = comp as InfoBindingSource;
        //                            if (ibs.DataSource == this) //find bindingsource of master
        //                            {
        //                                if (ibs.AutoApply)
        //                                {
        //                                    autoapply = true;
        //                                    continue;
        //                                }
        //                                else
        //                                {
        //                                    autoapply = false;
        //                                    break;
        //                                }
        //                            }
        //                            foreach (InfoRelation relation in ibs.Relations)
        //                            {
        //                                if (relation.RelationDataSet == this)// find view
        //                                {
        //                                    ibsview = ibs;
        //                                    break;
        //                                }
        //                            }
        //                        }
        //                    }
        //                    if (autoapply)
        //                    {
        //                        fRealDataSet.RejectChanges();
        //                        if (ibsview != null)
        //                        {
        //                            (ibsview.DataSource as LinqDataSet).RealDataSet.RejectChanges();
        //                            //clear edit flag...
        //                            ibsview.Reset_fInEdit();
        //                        }
        //                    }
        //                }
        //            }
        //            ApplyErrorEventArgs args = new ApplyErrorEventArgs(e);
        //            OnApplyError(args);
        //            blapplysuccess = false;
        //            if (!args.Cancel)
        //            {
        //                throw e;
        //            }
        //        }
        //        finally
        //        {
        //            if (this.Container != null)
        //            {
        //                foreach (IComponent comp in this.Container.Components)
        //                {
        //                    if (comp is InfoBindingSource)
        //                    {
        //                        InfoBindingSource bs = (InfoBindingSource)comp;
        //                        DataSet ds = new DataSet();
        //                        int m = bs.Relations.Count;
        //                        for (int n = 0; n < m; n++)
        //                        {
        //                            InfoRelation infoRel = bs.Relations[n];
        //                            ds = this.fRealDataSet;
        //                            if (infoRel.RelationDataSet.GetRealDataSet() == ds)
        //                            {
        //                                if (!infoRel.Active)
        //                                {
        //                                    infoRel.Active = this.RelationsActive;
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    OnAfterApplyUpdates(new EventArgs());
        //    return blapplysuccess;
        //}
    }

    public class LinqDataSetDesigner : ComponentDesigner
    {
        public LinqDataSetDesigner()
        {
            DesignerVerb saveVerb = new DesignerVerb("Save", new EventHandler(OnSave));
            this.Verbs.Add(saveVerb);
            DesignerVerb createVerb = new DesignerVerb("Save To Report", new EventHandler(OnCreate));
            this.Verbs.Add(createVerb);
            DesignerVerb createXSDVerb = new DesignerVerb("Create XSD File", new EventHandler(OnCreateXSD));
            this.Verbs.Add(createXSDVerb);
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        public override void InitializeNewComponent(System.Collections.IDictionary defaultValues)
        {
            LinqDataSet webDs = (LinqDataSet)this.Component;
            webDs.Guid = (Guid.NewGuid()).ToString();
        }

        public void OnCreate(object sender, EventArgs e)
        {
            OnSave(sender, e);
            if (this.Component != null)
            {
                InfoDataSet infoDataSet = (InfoDataSet)this.Component;
                if (infoDataSet.RealDataSet == null)
                {
                    infoDataSet.Active = true;
                }
                String s;
                RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\infolight\\eep.net");
                s = (String)rk.GetValue("Server Path");
                rk.Close();
                string xmlfile = s + "..\\..\\EEPNetReport\\";
                string str = infoDataSet.RemoteName;
                xmlfile = xmlfile + str.Substring(0, str.IndexOf('.')) + "_" + str.Substring(str.IndexOf('.') + 1) + ".xml";
                infoDataSet.RealDataSet.WriteXmlSchema(xmlfile);
            }
        }

        public virtual void OnCreateXSD(object sender, EventArgs e)
        {
            if (this.Component != null)
            {
                InfoDataSet infoDataSet = (InfoDataSet)this.Component;
                if (infoDataSet.RealDataSet == null)
                {
                    infoDataSet.Active = true;
                }
                String s;
                RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\infolight\\eep.net");
                s = (String)rk.GetValue("Server Path");
                rk.Close();

                string filePath = EditionDifference.ActiveDocumentPath();
                bool CreateFileSucess = true;
                string fileName = "";
                try
                {
                    fileName = filePath + infoDataSet.Site.Name + ".xsd";
                    infoDataSet.RealDataSet.WriteXmlSchema(fileName);
                }
                catch
                {
                    CreateFileSucess = false;
                    MessageBox.Show("Failed to create xsd file!");
                }
                finally
                {
                    if (CreateFileSucess && File.Exists(fileName))
                    {
                        EditionDifference.AddProjectItem(fileName);
                    }
                }
            }
        }

        public void OnSave(object sender, EventArgs e)
        {
            string keyName = "LinqDataSets";
            IDesignerHost designerHost = (IDesignerHost)this.GetService(typeof(IDesignerHost));

            CultureInfo culture = new CultureInfo("vi-VN");
            IResourceService resourceService = (IResourceService)designerHost.GetService(typeof(IResourceService));
            IResourceWriter resourceWriter = resourceService.GetResourceWriter(culture);
            IResourceReader resourceReader = resourceService.GetResourceReader(culture);
            IDictionaryEnumerator enumerator = resourceReader.GetEnumerator();

            XmlDocument xmlDoc = new XmlDocument();
            while (enumerator.MoveNext())
            {
                if (enumerator.Key.ToString() == keyName)
                {
                    string sXml = (string)enumerator.Value;
                    xmlDoc.LoadXml(sXml);
                    break;
                }
            }
            resourceReader.Close();

            // ---------------------------------------------------------------------
            XmlNode nLinqDSs = xmlDoc.SelectSingleNode("LinqDataSets");
            if (nLinqDSs == null)
            {
                nLinqDSs = CreateWDSsNode(xmlDoc);
                xmlDoc.AppendChild(nLinqDSs);
            }

            // ---------------------------------------------------------------------
            // 删除已经不存在的LinqDataSet。
            RemoveNotExisted(nLinqDSs);

            // ---------------------------------------------------------------------
            string name = this.Component.Site.Name;
            XmlNode nLinqDS = nLinqDSs.SelectSingleNode("LinqDataSet[@Name='" + name + "']");
            if (nLinqDS != null)
                nLinqDSs.RemoveChild(nLinqDS);

            nLinqDS = CreateLinqDSNode(xmlDoc);
            nLinqDSs.AppendChild(nLinqDS);

            // ---------------------------------------------------------------------
            resourceWriter.AddResource(keyName, xmlDoc.InnerXml);
            resourceWriter.Close();


            // 保存当前的文档
            EnvDTE.Document doc = EditionDifference.ActiveDocument();
            doc.Save(doc.FullName);
            doc.Saved = true;
        }

        private XmlNode CreateWDSsNode(XmlDocument xmlDoc)
        {
            XmlNode nLinqDataSets = xmlDoc.CreateElement("LinqDataSets");
            return nLinqDataSets;
        }

        private XmlNode CreateLinqDSNode(XmlDocument xmlDoc)
        {
            XmlElement linqDSNode = xmlDoc.CreateElement("LinqDataSet");

            XmlAttribute linqDSName = xmlDoc.CreateAttribute("Name");
            linqDSName.Value = this.Component.Site.Name;
            linqDSNode.Attributes.Append(linqDSName);

            // ---------------------------------------------------------------
            LinqDataSet linqDS = (LinqDataSet)this.Component;

            XmlNode nActive = xmlDoc.CreateElement("Active");
            nActive.InnerText = linqDS.Active.ToString();
            linqDSNode.AppendChild(nActive);

            XmlNode nPacketRecords = xmlDoc.CreateElement("PacketRecords");
            nPacketRecords.InnerText = linqDS.PacketRecords.ToString();
            linqDSNode.AppendChild(nPacketRecords);

            XmlNode nRemoteName = xmlDoc.CreateElement("RemoteName");
            nRemoteName.InnerText = linqDS.RemoteName;
            linqDSNode.AppendChild(nRemoteName);

            XmlNode nServerModify = xmlDoc.CreateElement("ServerModify");
            nServerModify.InnerText = linqDS.ServerModify.ToString();
            linqDSNode.AppendChild(nServerModify);

            XmlNode nAlwaysClose = xmlDoc.CreateElement("AlwaysClose");
            nAlwaysClose.InnerText = linqDS.AlwaysClose.ToString();
            linqDSNode.AppendChild(nAlwaysClose);

            XmlNode nState = xmlDoc.CreateElement("State");
            nState.InnerText = "true";
            linqDSNode.AppendChild(nState);

            return linqDSNode;
        }

        private void RemoveNotExisted(XmlNode node)
        {
            List<string> lists = new List<string>();
            LinqDataSet linqDS = (LinqDataSet)this.Component;
            ComponentCollection comps = linqDS.Site.Container.Components;
            foreach (object comp in comps)
            {
                if (comp is LinqDataSet)
                {
                    lists.Add(((Component)comp).Site.Name);
                }
            }

            foreach (XmlNode nod in node.ChildNodes)
            {
                string name = nod.Attributes["Name"].Value;
                if (lists.IndexOf(name) < 0)
                {
                    node.RemoveChild(nod);
                }
            }
        }
    }
}
